package com.adam.example.aggregation.metric;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.aggregations.Aggregate;
import co.elastic.clients.elasticsearch._types.aggregations.AvgAggregate;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import com.adam.example.ElasticsearchClientHolder;

import java.io.IOException;

public class AvgAggregationExample {

    public static void main(String[] args) throws IOException {
        ElasticsearchClient client = ElasticsearchClientHolder.getINSTANCE().initializeAndGetClient();

        SearchResponse<Void> searchResponse = client.search(builder -> builder
                        .index("test_books")
                        .size(0)
                        .aggregations("agg", aggregationBuilder -> aggregationBuilder
                                .avg(averageAggregationBuilder -> averageAggregationBuilder
                                        .field("price")
//                                        .missing(70.2)  //字段缺失时用来替换的值
                                )
                        )
                , Void.class);
        Aggregate aggregate = searchResponse.aggregations().get("agg");
        AvgAggregate avgAggregate = aggregate.avg();
        System.out.println(avgAggregate.value());

        ElasticsearchClientHolder.getINSTANCE().close();
    }

}
